<!-- 任务执行情况 -->
<template>
  <!--  $emit('update:visible',false)-->
  <el-dialog :title="connerName+'-视频录制'" :visible.sync="dialogVisible"
             :close-on-click-modal="false" width="80%" top="50px" :show-close="false">
    <div class="video-body-recode">
      <div class="video-list">
        <div class="camera_outer"
             v-loading="loading"
             element-loading-text="视频调用中…"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)">
          <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
          <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
        </div>
        <!--        计时器-->
        <div class="video-list-time" v-if="videoTime.status"><span>{{ videoTime.text }}</span></div>
      </div>
      <div class="columns">
        <div class="column" v-if="meetBtnStatus">
          <div class="record-settings">
            <vue-record-video mode="press" @stream="onVideoStream" @result="onVideoResult"/>
          </div>
        </div>
        <div v-else class="look-record-box">
          <span>会议时间已过，停止录制</span>
        </div>
        <div class="look-record-box" v-if="videoSrcOption">
          <span @click="previewVisible=true">查看录制</span>
        </div>
      </div>
      <previewVideo :visible.sync="previewVisible" :videoSrc="videoSrc" @remarkFn="remarkFn"></previewVideo>
      <progressVideo :visible.sync="progressVisible" :progressPercentNumber="progressPercentNumber"
                     :progressLine="progressLine"></progressVideo>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="checkVideoStatus" size="small">返回</el-button>
      <el-button type="primary" @click="onSubmitFn" size="small">确认并提交保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import previewVideo from "@/components/video/previewVideo";
import progressVideo from "@/components/video/progressVideo";

export default {
  name: 'video',
  props: ['visible', 'cornerVideoId', 'connerName'],
  components: {
    previewVideo,
    progressVideo
  },
  data() {
    return {
      // 弹窗
      previewVisible: false, // 预览视频
      progressVisible: false, // 进度条
      // end
      videoSrc: '', // 预览视频地址
      progressPercentNumber: 0, // 上传进度条
      progressLine: 1, // 上传进度 1 视频上传 2 采集上传 3 最后都成功了
      videoStatus: true, //  true 可以播放 false 停止播放

      recordMode: {
        audio: 'hold',
        video: 'press'
      },
      recordings: [],
      dialogVisible: this.visible,
      videoWidth: 900,
      videoHeight: 600,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      videoTime: {
        number: 0,
        text: '00:00',
        status: false
      },
      timeNumberFn: null, // 计时器
      videoSrcOption: '', // 视频源文件
      textarea: '', // 提交参数-备注
      loading: false,
      meetBtnStatus: false
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        console.log(this.visible, this.cornerVideoId)
        let n = this;
        this.loading = true
        console.log('获取当前会议时间：', this.meetTime)
        this.checkTime()
        setTimeout(() => {
          n.getCompetence()
        }, 500)
        // 需要加入判断是否上传成功，是否遗留之前的内容
        console.log('获取本地的数据内容')
        console.log(window.localStorage.getItem('videoFile'))
        // this.$refs.videoModelText.srcObject = null
        // this.$refs.videoModelText.src = JSON.parse(window.localStorage.getItem('videoFile'))
      } else {
        // 关闭页面视频
        clearInterval(this.timeNumberFn)
        this.stopNavigator(); // 关闭摄像头
        this.clearVideoStatus()
        this.previewVisible = false // 预览视频
        this.progressVisible = false // 进度条
        this.progressLine = 1
        this.videoStatus = false
      }
    }
  },
  created() {

  },
  methods: {
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this
      // this.thisCancas = document.getElementById('canvasCamera')
      // this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      var constraints = {
        audio: false,
        video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        _this.thisVideo.onloadedmetadata = function (e) {
          _this.thisVideo.play()
          setTimeout(() => {
            _this.loading = false
          }, 300)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    // 保存视频
    onSubmitFn() {
      let n = this
      if (!this.videoSrcOption) {
        this.$message.error('请录制视频')
        return
      }
      this.videoStatus = false // 停止播放
      this.progressVisible = true;

      const formData = new FormData();
      formData.append("file", this.videoSrcOption, 'cornerVideo.mp4');
      console.log('formData:', formData)
      if (!this.videoStatus) {
        return
      }
      // formData.append("token",sessionStorage.getItem("token"))
      // 上传视频源文件
      // 'http://120.78.228.13' + this.api.upload_img,
      this.axios({
        method: 'post',
        url: 'upload/oldupload',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'},
        onUploadProgress(progressEvent) {
          console.log('progressEvent:', progressEvent)
          if (progressEvent.lengthComputable) {
            let val = (progressEvent.loaded / progressEvent.total * 100).toFixed(0);
            console.log('改变值：', val)
            n.progressPercentNumber = val
          }
        }
      })
          .then(function (response) {
            console.log('上传成功了：', response)
            if (!response.data.code) {
              n.progressLine = 2

              n.saveVideoOptionFn(response.data.data.name)
            } else {
              alert(response.data.msg)
            }
          })
          .catch(function (error) {
            alert(JSON.stringify(error))
          })
    },
    // 提交数据内容
    async saveVideoOptionFn(videoSrc) {
      console.log('videoSrc:', videoSrc)
      let n = this;
      // corner_id 区角id video 视频地址
      let {data} = await this.$post(this.api.corner.video.add, {
        corner_id: this.cornerVideoId,
        video: videoSrc,
        remark: this.textarea
      }); //类型0游客1家长2老师
      console.log('提交数据内容：', data)
      n.progressLine = 3
      n.$message.success('提交成功')
      // 成功后清空页面数据内容
      this.clearVideoStatus()
      this.textarea = ''
      setTimeout(() => {
        n.previewVisible = false // 预览视频
        n.progressVisible = false // 进度条
      }, 1000)

    },
    removeRecord(index) {
      this.recordings.splice(index, 1)
    },
    // 点击了开始事件
    onVideoStream(stream) {
      console.log('开始录制:', stream);
      clearInterval(this.timeNumberFn)
      this.videoSrcOption = ''
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;
      // 将时间数据晴空
      let n = this;
      // 计时器开始计时 以60秒为单位
      this.videoSrc = ''
      this.videoTime.status = true;
      this.timeNumberFn = setInterval(() => {
        n.videoTime.number++
        n.videoTime.text = n.showTime(n.videoTime.number)
      }, 1000)
    },
    // 计算时间格式
    showTime(val) {
      if (val < 60) {
        return val < 10 ? '00:0' + val : '00:' + val;
      } else {
        let min_total = Math.floor(val / 60); // 分钟
        let sec = Math.floor(val % 60); // 余秒
        if (min_total < 60) {
          return (min_total < 10 ? '0' + min_total : min_total) + ":" + (sec < 10 ? '0' + sec : sec);
        } else {
          let hour_total = Math.floor(min_total / 60); // 小时数
          let min = Math.floor(min_total % 60); // 余分钟
          return (hour_total < 10 ? '0' + hour_total : hour_total) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec);
        }
      }
    },
    onVideoResult(data) {
      console.log('结束了', window.URL.createObjectURL(data))
      // let videoList = JSON.parse(window.localStorage.getItem('videoFile'))
      let videoOption = [{name: '视频采集', videoSrc: window.URL.createObjectURL(data)}] // revokeObjectURL
      window.localStorage.setItem('videoFile', JSON.stringify(videoOption))
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;

      this.videoSrc = window.URL.createObjectURL(data)
      this.previewVisible = true

      this.videoSrcOption = data // 最后上传的视频源
      clearInterval(this.timeNumberFn)
    },
    onResult(data) {
      this.recordings.push({
        src: window.URL.createObjectURL(data)
      })
    },
    clearVideoStatus() {
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;
      this.videoSrcOption = '' // 123
    },
    // 检查是否再录视频
    checkVideoStatus() {
      if (this.videoTime.status) {
        this.$message.error('视频录制中请先停止')
      } else {
        this.$emit('update:visible', false)
      }
    },
    remarkFn(option) {
      this.textarea = option;
    }
  },
  mounted() {
    console.log('获取按键视频')
  }
}
</script>
<style scoped>
.camera_outer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  background: #333;
}

.textareaBox textarea {
  height: 70px;
}

.look-record-box {
  text-align: center;
  color: #3e89ff;
  text-decoration: underline;
  padding-top: 20px;
}

.look-record-box span {
  cursor: pointer;
  padding: 10px;
}

.video-body-recode {
  position: relative;
}


.video-list {
  position: relative;
}

.video-list-time {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: rgba(0, 0, 0, .5);
  text-align: center;
  padding: 10px 0;
}

.video-list-time span {
  color: #fff;
  font-weight: bold;
  font-size: 26px;
}

</style>
<!-- 任务执行情况 -->
<template>
  <!--  $emit('update:visible',false)-->
  <el-dialog :title="connerName+'-视频采集'" :visible.sync="dialogVisible"
             :close-on-click-modal="false" width="80%" top="50px" :show-close="false">
    <div class="video-body-recode">
      <div class="video-list">
        <div class="camera_outer"
             v-loading="loading"
             element-loading-text="视频调用中…"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)">
          <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
          <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
        </div>
        <!--        计时器-->
        <div class="video-list-time" v-if="videoTime.status"><span>{{ videoTime.text }}</span></div>
      </div>
      <div class="columns">
        <div class="column">
          <div class="record-settings">
            <vue-record-video mode="press" @stream="onVideoStream" @result="onVideoResult"/>
          </div>
        </div>
        <div class="look-record-box" v-if="videoSrcOption">
          <span @click="previewVisible=true">查看录制</span>
        </div>
      </div>
      <previewVideo :visible.sync="previewVisible" :videoSrc="videoSrc" @remarkFn="remarkFn"
                    typeOption="videoMeet"></previewVideo>
      <progressVideo :visible.sync="progressVisible" :progressPercentNumber="progressPercentNumber"
                     :progressLine="progressLine"></progressVideo>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="checkVideoStatus" size="small">返回</el-button>
      <el-button type="primary" @click="onSubmitFn" size="small">确认并提交保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import previewVideo from "../video/previewVideo";
import progressVideo from "../video/progressVideo";

export default {
  name: 'video',
  props: ['visible', 'cornerVideoId', 'connerName'],
  components: {
    previewVideo,
    progressVideo
  },
  data() {
    return {
      // 弹窗
      previewVisible: false, // 预览视频
      progressVisible: false, // 进度条
      // end
      videoSrc: '', // 预览视频地址
      progressPercentNumber: 0, // 上传进度条
      progressLine: 1, // 上传进度 1 视频上传 2 采集上传 3 最后都成功了
      videoStatus: true, //  true 可以播放 false 停止播放

      recordMode: {
        audio: 'hold',
        video: 'press'
      },
      recordings: [],
      dialogVisible: this.visible,
      videoWidth: 900,
      videoHeight: 600,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      videoTime: {
        number: 0,
        text: '00:00',
        status: false
      },
      timeNumberFn: null, // 计时器
      videoSrcOption: '', // 视频源文件
      textarea: '', // 提交参数-备注
      loading: false
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        console.log(this.visible, this.cornerVideoId)
        let n = this;
        this.loading = true
        setTimeout(() => {
          n.getCompetence()
        }, 500)
        // 需要加入判断是否上传成功，是否遗留之前的内容
        console.log('获取本地的数据内容')
        console.log(window.localStorage.getItem('videoFile'))
        // this.$refs.videoModelText.srcObject = null
        // this.$refs.videoModelText.src = JSON.parse(window.localStorage.getItem('videoFile'))
      } else {
        // 关闭页面视频
        clearInterval(this.timeNumberFn)
        this.stopNavigator(); // 关闭摄像头
        this.clearVideoStatus()
        this.previewVisible = false // 预览视频
        this.progressVisible = false // 进度条
        this.progressLine = 1
        this.videoStatus = false
      }
    }
  },
  created() {

  },
  methods: {
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this
      // this.thisCancas = document.getElementById('canvasCamera')
      // this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      var constraints = {
        audio: false,
        video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        _this.thisVideo.onloadedmetadata = function (e) {
          _this.thisVideo.play()
          setTimeout(() => {
            _this.loading = false
          }, 300)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    // 保存视频
    onSubmitFn() {
      let n = this
      if (!this.videoSrcOption) {
        this.$message.error('请录制视频')
        return
      }
      this.videoStatus = false // 停止播放
      this.progressVisible = true;

      const formData = new FormData();
      formData.append("file", this.videoSrcOption, 'cornerVideo.mp4');
      console.log('formData:', formData)
      // formData.append("token",sessionStorage.getItem("token"))
      // 上传视频源文件
      this.axios({
        method: 'post',
        url: 'upload/oldupload',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'},
        onUploadProgress(progressEvent) {
          console.log('progressEvent:', progressEvent)
          if (progressEvent.lengthComputable) {
            let val = (progressEvent.loaded / progressEvent.total * 100).toFixed(0);
            console.log('改变值：', val)
            n.progressPercentNumber = val
          }
        }
      })
          .then(function (response) {
            console.log('上传成功了：', response)
            if (!response.data.code) {
              n.progressLine = 2

              n.saveVideoOptionFn(response.data.data.name)
            } else {
              alert(response.data.msg)
            }
          })
          .catch(function (error) {
            alert(JSON.stringify(error))
          })
    },
    // 提交数据内容
    async saveVideoOptionFn(videoSrc) {
      let n = this;
      // corner_id 区角id video 视频地址
      let data = await this.$post(this.api.videoMeet.videoUpload, {
        id: this.cornerVideoId,
        video: videoSrc
      });
      console.log('提交数据内容：', data)
      if (!data.code) {
        n.progressLine = 3
        n.$message.success(data.msg)
        // 成功后清空页面数据内容
        this.clearVideoStatus()
        this.textarea = ''
        setTimeout(() => {
          n.previewVisible = false // 预览视频
          n.progressVisible = false // 进度条
        }, 1000)
      } else {
        alert(data.msg)
      }
    },
    removeRecord(index) {
      this.recordings.splice(index, 1)
    },
    // 点击了开始事件
    onVideoStream(stream) {
      console.log('开始录制:', stream);
      clearInterval(this.timeNumberFn)
      this.videoSrcOption = ''
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;
      // 将时间数据晴空
      let n = this;
      // 计时器开始计时 以60秒为单位
      this.videoSrc = ''
      this.videoTime.status = true;
      this.timeNumberFn = setInterval(() => {
        n.videoTime.number++
        n.videoTime.text = n.showTime(n.videoTime.number)
      }, 1000)
    },
    // 计算时间格式
    showTime(val) {
      if (val < 60) {
        return val < 10 ? '00:0' + val : '00:' + val;
      } else {
        let min_total = Math.floor(val / 60); // 分钟
        let sec = Math.floor(val % 60); // 余秒
        if (min_total < 60) {
          return (min_total < 10 ? '0' + min_total : min_total) + ":" + (sec < 10 ? '0' + sec : sec);
        } else {
          let hour_total = Math.floor(min_total / 60); // 小时数
          let min = Math.floor(min_total % 60); // 余分钟
          return (hour_total < 10 ? '0' + hour_total : hour_total) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec);
        }
      }
    },
    onVideoResult(data) {
      console.log('结束了', window.URL.createObjectURL(data))
      // let videoList = JSON.parse(window.localStorage.getItem('videoFile'))
      let videoOption = [{name: '视频采集', videoSrc: window.URL.createObjectURL(data)}] // revokeObjectURL
      window.localStorage.setItem('videoFile', JSON.stringify(videoOption))
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;

      this.videoSrc = window.URL.createObjectURL(data)
      this.previewVisible = true

      this.videoSrcOption = data // 最后上传的视频源
      clearInterval(this.timeNumberFn)
    },
    onResult(data) {
      this.recordings.push({
        src: window.URL.createObjectURL(data)
      })
    },
    clearVideoStatus() {
      this.videoTime.status = false;
      this.videoTime.text = '00:00';
      this.videoTime.number = 0;
      this.videoSrcOption = '' // 123
    },
    // 检查是否再录视频
    checkVideoStatus() {
      if (this.videoTime.status) {
        this.$message.error('视频录制中请先停止')
      } else {
        this.$emit('update:visible', false)
      }
    },
    remarkFn(option) {
      this.textarea = option;
    },
    checkTime() {
      // 验证时间是否过期
      let str = this.meetTime.replace(/-/g, "/");
      let curDate = new Date(),
          endDate = new Date(str + ' 23:59');
      if (curDate <= endDate) {
        console.log('时间之前,可以录制')
        this.meetBtnStatus = true
      } else {
        console.log('超时了，停止录制')
        this.meetBtnStatus = false
      }
    }
  },
  mounted() {
    console.log('获取按键视频')
  }
}
</script>
<style scoped>
.camera_outer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  background: #333;
}

.textareaBox textarea {
  height: 70px;
}

.look-record-box {
  text-align: center;
  color: #3e89ff;
  text-decoration: underline;
  padding-top: 20px;
}

.look-record-box span {
  cursor: pointer;
  padding: 10px;
}

.video-body-recode {
  position: relative;
}


.video-list {
  position: relative;
}

.video-list-time {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: rgba(0, 0, 0, .5);
  text-align: center;
  padding: 10px 0;
}

.video-list-time span {
  color: #fff;
  font-weight: bold;
  font-size: 26px;
}

</style>
